package com.ruoyi.pos.service.impl.print;

import com.ruoyi.pos.domain.print.PosPrintScheme;
import com.ruoyi.pos.domain.dto.print.request.PrintSchemeQueryRequest;
import com.ruoyi.pos.domain.dto.print.response.PrintSchemeResponse;
import com.ruoyi.pos.domain.dto.common.response.BasePageResponse;
import com.ruoyi.pos.mapper.print.PosPrintSchemeMapper;
import com.ruoyi.pos.service.print.IPosPrintSchemeService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * POS打印方案Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-01-30
 */
@Service
@Transactional(transactionManager = "posTransactionManager")
public class PosPrintSchemeServiceImpl implements IPosPrintSchemeService {

    @Autowired
    private PosPrintSchemeMapper posPrintSchemeMapper;

    /**
     * 查询单个打印方案信息
     * 支持根据ID、编码查询
     * 
     * @param request 查询请求
     * @return 打印方案信息
     */
    @Override
    public PrintSchemeResponse getPrintScheme(PrintSchemeQueryRequest request) {
        PosPrintScheme printScheme = null;
        
        if (request.getSchemeId() != null) {
            printScheme = posPrintSchemeMapper.selectPosPrintSchemeById(request.getSchemeId());
        } else if (StringUtils.isNotEmpty(request.getSchemeName())) {
            // 根据方案名称查询
            PosPrintScheme queryScheme = new PosPrintScheme();
            queryScheme.setSchemeName(request.getSchemeName());
            List<PosPrintScheme> schemes = posPrintSchemeMapper.selectPosPrintSchemeList(queryScheme);
            if (!schemes.isEmpty()) {
                printScheme = schemes.get(0);
            }
        }
        
        if (printScheme == null) {
            return null;
        }
        
        return convertToResponse(printScheme);
    }

    /**
     * 分页查询打印方案列表
     * 
     * @param request 查询请求
     * @return 分页响应
     */
    @Override
    public BasePageResponse<PrintSchemeResponse> queryPrintSchemes(PrintSchemeQueryRequest request) {
        PosPrintScheme printScheme = new PosPrintScheme();
        printScheme.setSchemeId(request.getSchemeId());
        printScheme.setSchemeName(request.getSchemeName());
        printScheme.setSchemeType(request.getSchemeType());
        printScheme.setTemplateType(request.getTemplateType());
        printScheme.setStatus(request.getIsEnabled());
        
        List<PosPrintScheme> printSchemes = posPrintSchemeMapper.selectPosPrintSchemeList(printScheme);
        List<PrintSchemeResponse> responses = printSchemes.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
        
        return new BasePageResponse<>(responses, printSchemes.size());
    }

    /**
     * 验证打印方案模板语法
     * 
     * @param schemeId 方案ID
     * @return 验证结果
     */
    @Override
    public boolean validatePrintSchemeTemplate(Long schemeId) {
        try {
            PosPrintScheme printScheme = posPrintSchemeMapper.selectPosPrintSchemeById(schemeId);
            if (printScheme == null) {
                return false;
            }
            
            String templateContent = printScheme.getTemplateContent();
            if (StringUtils.isEmpty(templateContent)) {
                return false;
            }
            
            // 简单的模板语法验证
            // 检查是否包含必要的占位符
            return templateContent.contains("${") && templateContent.contains("}");
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取打印方案预览内容
     * 
     * @param schemeId 方案ID
     * @param sampleData 示例数据
     * @return 预览内容
     */
    @Override
    public String getPrintSchemePreview(Long schemeId, String sampleData) {
        try {
            PosPrintScheme printScheme = posPrintSchemeMapper.selectPosPrintSchemeById(schemeId);
            if (printScheme == null) {
                return "打印方案不存在";
            }
            
            String templateContent = printScheme.getTemplateContent();
            if (StringUtils.isEmpty(templateContent)) {
                return "模板内容为空";
            }
            
            // 简单的模板替换预览
            // 这里可以根据实际需求实现更复杂的模板引擎
            String preview = templateContent;
            if (StringUtils.isNotEmpty(sampleData)) {
                // 简单的占位符替换示例
                preview = preview.replace("${storeName}", "示例商店")
                               .replace("${transactionNo}", "TXN202501300001")
                               .replace("${totalAmount}", "100.00")
                               .replace("${cashierName}", "收银员001");
            }
            
            return preview;
        } catch (Exception e) {
            return "预览生成失败: " + e.getMessage();
        }
    }

    /**
     * 转换实体为响应DTO
     * 
     * @param printScheme 打印方案实体
     * @return 打印方案响应DTO
     */
    private PrintSchemeResponse convertToResponse(PosPrintScheme printScheme) {
        PrintSchemeResponse response = new PrintSchemeResponse();
        BeanUtils.copyBeanProp(response, printScheme);
        return response;
    }
}
